using LF.Application.Services.interfaces;
using LF.Domain.Entities;
using LF.Domain.Services;
using LF.Application.Services.Iml;
using LF.Shared.Dtos.Out;
using LF.Shared.Dtos.Input;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.ObjectMapping;
using Volo.Abp.Uow;
using System;
using System.Collections.Generic;
using System.Linq;
using LF.Application.Extend;

namespace LF.Application.Services.Iml
{
    [Authorize]
    [ApiExplorerSettings(GroupName = SwaggerGroup.Sys)]
    public class DeptmentService : BaseService, IDeptmentService
    {
        private readonly IDeptmentManagerService _manager;

        public DeptmentService(
            IDeptmentManagerService manager,
            IObjectMapper<LFModule> mapper,
            IGlobalManagerService globalManager) : base(mapper, globalManager)
        {
            _manager = manager;
        }
        
        [LFAuthorize("获取部门列表", "system:dept:list")]
        public Result<List<DeptmentOut>> List()
        {
            var depts = _manager.GetDeptTree();
            var result = _mapper.Map<List<Deptment>, List<DeptmentOut>>(depts);
            return Ok(result);
        }

        public Result<DeptmentSearchOut> Deptments([FromQuery]DeptmentSearch search)
        {
            var result = _manager.All(search.Index, search.PageSize, search.Key);
            var list = _mapper.Map<List<Deptment>, List<DeptmentOut>>(result);
            var count = _manager.Count(search.Key);
            return Ok(new DeptmentSearchOut { Items = list, TotalCount = count });
        }

        [LFAuthorize("获取部门详情", "system:dept:read")]
        public Result<DeptmentOut> Get(Guid id)
        {
            var item = _globalManager.Get<Deptment>(id);
            if (item == null)
                return Error<DeptmentOut>("部门不存在");

            var result = _mapper.Map<Deptment, DeptmentOut>(item);
            return Ok(result);
        }
        [LFAuthorize("创建部门信息", "system:dept:create")]
        public Result Create([FromBody]DeptmentOut dept)
        {
            // 自动生成部门编码
            dept.DeptCode = _manager.GenerateDeptCode(dept.SupDeptId);

            var model = _mapper.Map<DeptmentOut, Deptment>(dept);
            model.Id = Guid.NewGuid();
            
            if (_globalManager.Insert(model))
                return Ok();
            else
                return Error("创建失败");
        }
        [LFAuthorize("编辑部门信息", "system:dept:create")]
        public Result Update(Guid id, [FromBody]DeptmentOut dept)
        {
            var existingDept = _globalManager.Get<Deptment>(id);
            if (existingDept == null)
                return Error("部门不存在");

            // 检查是否将部门设为自己的子部门
            if (dept.SupDeptId == id)
                return Error("不能将部门设为自己的子部门");

            // 检查是否将部门设为其子部门的子部门
            var childDepts = _manager.GetDeptWithChildren(id);
            if (childDepts.Any(d => d.Id == dept.SupDeptId))
                return Error("不能将部门设为其子部门的子部门");

            var model = _mapper.Map<DeptmentOut, Deptment>(dept);
            model.Id = id;
            model.DeptCode = existingDept.DeptCode; // 保持原有编码不变
            if (_globalManager.Update(model))
                return Ok();
            else
                return Error("更新失败");
        }
        [LFAuthorize("删除部门", "system:dept:delete")]
        public Result Delete(Guid id)
        {
            var childDepts = _manager.GetDeptWithChildren(id);
            if (childDepts.Count > 1) // 如果大于1说明有子部门
                return Error("该部门下存在子部门,请先删除子部门");

            if (_globalManager.RealDelete<Deptment>(id))
                return Ok();
            else
                return Error("删除失败");
        }
    }
}
